using System;
using System.Threading;
using WCell.Constants;
using WCell.Constants.World;
using WCell.Core.Timers;
using WCell.RealmServer.Battlegrounds;
using WCell.RealmServer.Entities;
using WCell.RealmServer.Formulas;
using WCell.RealmServer.Global;
using WCell.RealmServer.Network;
using WCell.RealmServer.Handlers;

namespace WCell.RealmServer.Instances
{
	public delegate void InstanceDelegate(BaseInstance instance);

	/// <summary>
	/// The base class for all WoW-style "Instances" (Normal, Heroic, Raid etc)
	/// </summary>
	public abstract class BaseInstance : InstancedRegion
	{
		protected DungeonMode m_dungeonMode;
		protected IInstanceHolderSet m_owner;
		protected DateTime m_expiryTime;

		protected BaseInstance()
		{
		}

		protected internal override void InitRegion()
		{
			base.InitRegion();

			var secs = m_regionInfo.GetExpiryTime(DungeonMode);
			if (secs > 0)
			{
				// TODO: Set expiry time correctly
				//m_expiryTime = InstanceMgr.
			}
		}

		public bool Expires
		{
			get { return m_expiryTime != default(DateTime); }
		}

		public DateTime ExpiryTime
		{
			get { return m_expiryTime; }
		}

		/// <summary>
		/// Difficulty of the instance
		/// </summary>
		public DungeonMode DungeonMode
		{
			get { return m_dungeonMode; }
			set { m_dungeonMode = value; }
		}

		public IInstanceHolderSet Owner
		{
			get { return m_owner; }
			set { m_owner = value; }
		}

		public override bool CanEnter(Character chr)
		{
			if (base.CanEnter(chr))
			{
				var leader = Owner.InstanceLeader;
				return leader != null && chr.IsAlliedWith(leader);
			}
			return false;
		}

		public override void TeleportOutside(Character chr)
		{
			chr.TeleportToNearestGraveyard();
		}

		public override void DeleteNow()
		{
			World.RemoveInstance(this);
			base.DeleteNow();
		}

		protected override void Dispose()
		{
			base.Dispose();
			m_owner = null;
		}

		public override string ToString()
		{
			var ownerStr = "";
			if (Owner != null && Owner.InstanceLeader != null)
			{
				ownerStr = " - Owned by: " + Owner.InstanceLeader.Name;
			}
			return base.ToString() + ((m_dungeonMode == DungeonMode.Heroic ? " [Heroic]" : "") + ownerStr);
		}
	}
}
